import express from 'express';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import { Jwt } from 'jsonwebtoken';
import morgan from 'morgan';
import createHttpError from 'http-errors';
import bodyParser from 'body-parser';
import indexRouter from './controllers/index.js';
import mongoRouter from './controllers/mongodb.js';
import cors from 'cors';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
import dotenv from 'dotenv';

import type { Response, Request, NextFunction } from 'express';
// 获取 __dirname 的 ESM 写法
const __dirname = dirname(fileURLToPath(import.meta.url));
dotenv.config({ path: path.join(__dirname, '../.env') });

const app = express();

// 记录日志
const loggerStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));
app.use(morgan('combined', { stream: loggerStream }));

// 路由配置
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('signed'));
app.use(
  session({
    secret: 'secret',
    name: 'sid',
    cookie: {
      maxAge: 1000,
    },
  }),
);
app.use('/www', express.static(path.join(__dirname, '../static')));
app.use('/', indexRouter);
app.use('/mongo', mongoRouter);

// catch 404 and forward to error handler
app.use((req: Request, res: Response, next: NextFunction) => {
  next(createHttpError(404, '页面不在地球上~'));
});
// error handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  (res.locals as any).message = err.message;
  (res.locals as any).error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500).send(err.message);
});

export { app };
